<template>
  <div class="anniversary-detail-view" :style="{ backgroundImage: 'url(' + backgroundImageUrl + ')' }">
    <AppHeader title="纪念日详情">
      <template #left>
        <el-button circle @click="router.back()">
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
      </template>
    </AppHeader>

    <div v-if="anniversary" class="detail-content">
      <h2>{{ anniversary.title }}</h2>
      <div class="target-date">{{ dayjs(anniversary.targetDate).format('YYYY年MM月DD日') }}</div>
      <div class="countdown">{{ countdownDisplay }}</div>
      <div class="description" v-if="anniversary.description">{{ anniversary.description }}</div>
    </div>
    <div v-else class="detail-content">
      <p>加载中或纪念日不存在...</p>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router' // Import useRoute and useRouter
import axios from 'axios'
import dayjs from 'dayjs' // 使用 dayjs 库处理日期和时间
import duration from 'dayjs/plugin/duration' // 引入 duration 插件
import AppHeader from '../components/AppHeader.vue'
import { ArrowLeft } from '@element-plus/icons-vue'

dayjs.extend(duration)

export default {
  name: 'AnniversaryDetailView',
  components: {
    AppHeader,
    ArrowLeft,
  },
  setup() {
    const route = useRoute()
    const router = useRouter() // Initialize useRouter
    const anniversary = ref(null)
    const countdownDisplay = ref('加载中...')
    let countdownTimer = null
    // Set the fixed background image URL
    const backgroundImageUrl = ref('/pics/2b5653be750a724d2117708a5e84bb8.jpg')

    const fetchAnniversaryDetail = async (id) => {
      try {
        const response = await axios.get(`http://localhost:8080/anniversary/query`, {
          params: { id: id }
        })
        // Assuming the anniversary data is directly in response.data if the request is successful
        if (response.data && Object.keys(response.data).length > 0) { // Check if response.data is not empty object
          anniversary.value = response.data
          startCountdown()
        } else {
           anniversary.value = null;
           countdownDisplay.value = '纪念日未找到或数据为空';
        }
      } catch (error) {
        console.error('Error fetching anniversary detail:', error)
        anniversary.value = null;
        countdownDisplay.value = '加载失败';
      }
    }

    const calculateCountdown = (targetDate) => {
      const now = dayjs()
      const target = dayjs(targetDate)
      if (target.isBefore(now)) {
        return '已过期'
      }

      const diff = target.diff(now)
      const duration = dayjs.duration(diff)

      const days = Math.floor(duration.asDays())
      const hours = duration.hours() % 24;
      const minutes = duration.minutes() % 60;
      const seconds = duration.seconds() % 60;

       // Handle cases where duration might be negative if target is slightly in the past
      if (days < 0 || hours < 0 || minutes < 0 || seconds < 0) {
           return '已过期';
      }

      return `${days}天${String(hours).padStart(2, '0')}时${String(minutes).padStart(2, '0')}分${String(seconds).padStart(2, '0')}秒`
    }

    const startCountdown = () => {
      stopCountdown(); // Clear any existing timer
       if (anniversary.value) {
          countdownDisplay.value = calculateCountdown(anniversary.value.targetDate)
          countdownTimer = setInterval(() => {
            countdownDisplay.value = calculateCountdown(anniversary.value.targetDate)
          }, 1000)
       }
    }

    const stopCountdown = () => {
      if (countdownTimer) {
        clearInterval(countdownTimer)
        countdownTimer = null
      }
    }

    onMounted(() => {
      const anniversaryId = route.params.id
      if (anniversaryId) {
        fetchAnniversaryDetail(anniversaryId)
      }
    })

    onUnmounted(() => {
      stopCountdown()
    })

    return {
      anniversary,
      countdownDisplay,
      backgroundImageUrl,
      dayjs,
      router, // Expose router for back button
    }
  }
}
</script>

<style scoped>
.anniversary-detail-view {
  min-height: 100vh;
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: white; /* White text for better contrast on background */
  text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.5); /* Add text shadow for readability */
  padding-top: 60px; /* Padding for fixed header */
}

.detail-content {
  flex-grow: 1; /* Allow content to take up available space */
  display: flex;
  flex-direction: column;
  justify-content: center; /* Center content vertically */
  align-items: center; /* Center content horizontally */
  text-align: center;
  padding: 20px;
  background-color: rgba(0, 0, 0, 0.3); /* Semi-transparent overlay for readability */
  border-radius: 10px;
  margin-top: 20px; /* Space below header */
  margin-bottom: 20px; /* Space above bottom */
}

.detail-content h2 {
  font-size: 28px;
  margin-bottom: 10px;
  color: white; /* Ensure title is white */
}

.target-date {
  font-size: 18px;
  margin-bottom: 20px;
}

.countdown {
  font-size: 32px; /* Smaller font size */
  font-weight: bold;
  margin-bottom: 20px;
  white-space: nowrap; /* Prevent text wrapping */
}

.description {
  font-size: 16px;
  max-width: 600px; /* Limit description width */
  line-height: 1.6;
}
</style> 